package cn.strive.eams.user.service.impl;

import cn.strive.eams.base.enmus.RoleEnum;
import cn.strive.eams.base.exception.ServiceException;
import cn.strive.eams.base.response.JsonResult;
import cn.strive.eams.base.response.StatusCode;
import cn.strive.eams.user.mapper.UserMapper;
import cn.strive.eams.user.pojo.dto.*;
import cn.strive.eams.user.pojo.entity.User;
import cn.strive.eams.user.pojo.vo.UserVO;
import cn.strive.eams.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;


    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录业务,参数:{}", userLoginParam);
        UserVO userVO = userMapper.selectByJobNumber(userLoginParam.getJobNumber());
        if (userVO == null) {
            log.warn("工号不存在:{}", userLoginParam.getJobNumber());
            throw new ServiceException(StatusCode.JOB_NUMBER_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())) {
            log.warn("用户名或密码错误:{}", userLoginParam.getPassword());
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        log.debug("用户登录业务,结果:{}", userVO);
        return userVO;
    }

    @Override
    public UserVO backup(UserLoginParam userLoginParam) {
        log.debug("用户登录业务,参数:{}", userLoginParam);
        UserVO userVO = userMapper.selectByPhone(userLoginParam.getPhone());
        if (userVO == null) {
            log.warn("工号不存在:{}", userLoginParam.getPhone());
            throw new ServiceException(StatusCode.PHONE_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())) {
            log.warn("用户名或密码错误:{}", userLoginParam.getPassword());
            throw new ServiceException(StatusCode.PASSWORD_PHONE_ERROR);
        }
        log.debug("用户登录业务,结果:{}", userVO);
        return userVO;
    }

    @Override
    public List<UserVO> selectAll(UserQuery userQuery) {
        log.info("查询员工信息:userQuery={}", userQuery);
        return userMapper.selectAll(userQuery);
    }

    @Override
    public void saveInfo(UserSaveParam userSaveParam) {
        log.debug("员工信息业务,参数:{}", userSaveParam);

        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);

        if (user.getId() == null) {
            if (isPhoneExist(userSaveParam.getPhone())) {
                log.warn("手机号已存在:{}", userSaveParam.getPhone());
                throw new ServiceException(StatusCode.PHONE_EXIST);
            }
            user.setJobNumber(generateJobNumber());
            user.setPassword("123456");
            user.setAvatar("/base/base.jpg");
            user.setCreateTime(new Date());
            userMapper.save(user);
        } else { // 更新
            if (userSaveParam.getLeader() == null) {
                ;
                user.setLeader(null);
                user.setUpdateTime(new Date());
                userMapper.update(user);
                log.debug("员工信息更新业务,结果:{}", user);
            }
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }
        log.debug("员工信息业务,结果:{}", user);
    }

    private String generateJobNumber() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentDateStr = LocalDate.now().format(formatter);

        // 初始化四位数字部分，从0000开始
        int numberPart = 0;

        String JobNumber;
        do {
            // 将数字部分格式化为四位数，不足的前面补零
            String formattedNumber = String.format("%04d", numberPart);
            JobNumber = currentDateStr + formattedNumber;

            // 检查是否有重复的昵称
            if (!isJobNumberExists(JobNumber)) {
                break;
            }
            // 如果存在重复，则将数字部分增加10
            numberPart += 10;
        } while (true);

        return JobNumber;
    }

    private boolean isJobNumberExists(String username) {
        return userMapper.existsByJobNumber(username) > 0;
    }

    @Override
    public void savePassword(UserSavePassword userSavePassword) {
        log.debug("修改密码:employeeSavePassword={}", userSavePassword);
        UserVO userVO = userMapper.selectById(userSavePassword.getId());
        if (userVO.getPassword().equals(userSavePassword.getOldPassword())) {
            User user = new User();
            user.setId(userSavePassword.getId());
            user.setPassword(userSavePassword.getNewPassword());
            user.setUpdateTime(new Date());
            userMapper.update(user);
        } else {
            log.warn("旧密码错误:{}", userSavePassword.getOldPassword());
            throw new ServiceException(StatusCode.OLD_PASSWORD_ERROR);
        }
    }

    @Override
    public void updateStatus(Long id, String status) {
        log.debug("更新员工状态:id={},status={}", id, status);
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void updatePassword(Long id) {
        log.debug("更新员工密码:id={}", id);
        User user = new User();
        user.setId(id);
        user.setPassword("123456");
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void delete(Long id) {
        log.debug("删除员工信息:id={}", id);
        userMapper.delete(id);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        log.debug("批量删除员工信息:ids={}", ids);
        for (Long id : ids) {
            userMapper.delete(id);
        }
    }

    @Override
    public List<UserVO> selectLeader(LeaderQuery leaderQuery) {
        if (leaderQuery == null || leaderQuery.getRole() == null) {
            throw new IllegalArgumentException("leaderQuery or its role cannot be null");
        }

        log.debug("查询领导信息: leaderQuery={}", leaderQuery);

        try {
            // 确保 RoleEnum.fromCode 不会返回 null
            RoleEnum role = RoleEnum.fromCode(leaderQuery.getRole());
            if (role == null) {
                log.error("不支持的角色代码: {}", leaderQuery.getRole());
                throw new IllegalArgumentException("Unsupported role code: " + leaderQuery.getRole());
            }

            switch (role) {
                case INSTRUCTOR:
                    return userMapper.select_HEADER_OF_SUBJECT(leaderQuery);
                case TEACHER:
                    return userMapper.select_DIRECTOR_OF_TEACHER(leaderQuery);
                case HEADER_OF_SUBJECT:
                case DIRECTOR_OF_TEACHER:
                    return userMapper.select_MANAGEMENT_TEACHER(leaderQuery);
                case Driver:
                    return userMapper.select_ALLOCATION(leaderQuery);
                case HOUSEMASTER:
                case MAINTENANCE_MAN:
                case MANAGEMENT_TEACHER:
                case LOGISTICS:
                case DIRECTOR_OF_FINANCE:
                case ALLOCATION:
                    return null;
                default:
                    log.warn("未处理的角色类型: {}", role);
                    throw new IllegalArgumentException("Unhandled role type: " + role);
            }
        } catch (Exception e) {
            log.error("查询领导信息时发生错误", e);
            throw new RuntimeException("查询领导信息时发生错误", e);
        }
    }

    @Override
    public List<UserVO> selectAudit(Long leader) {
        log.debug("根据上级ID查询用户业务,参数:{}", leader);
        ArrayList<UserVO> userVOList = new ArrayList<>();
        UserVO auditUser1 = userMapper.selectById(leader);
        userVOList.add(auditUser1);
        if (auditUser1 != null && auditUser1.getLeader() != null) {
            UserVO auditUser2 = userMapper.selectById(auditUser1.getLeader());
            userVOList.add(auditUser2);
        }
        return userVOList;
    }

    @Override
    public List<UserVO> selectAllocation(Long role) {
        log.debug("根据角色查询用户业务,参数:{}", role);
        return userMapper.selectAllocation(role);
    }

    @Override
    public List<UserVO> selectDrivers() {
        log.debug("查询司机业务");
        return userMapper.selectDrivers();
    }


    private boolean isPhoneExist(String phone) {
        UserVO userVO = userMapper.selectByPhone(phone);
        return userVO != null;
    }
}
